/*
 * SQL Section 
 * Child class for setConnection.java
 * Contains methods to send sql query and to close connection
 */

import java.sql.*;

/**
 * 
 * @author Master
 */
public class Query extends SqlSetConnection {

    /*
     * Connecition properties
     */
    private String query;
    public static Connection connection = null;

    /*
     * Constructor
     * Send connection to class propery
     * Write debug info from parent's debug property
     */
    public Query(String driver, String server, String props, String query) {
        super(driver, server, props);
        this.query = query;

        // Attempt to establish connection
        SqlSetConnection db = null;
        try {
            db = new SqlSetConnection(this.driver, this.server, this.props);
            connection = db.connect();
            // Send to ancestor debug info from parent class.
            debug(db.debug);
        } catch (Exception e) {
            debug(e.getMessage());
        }

    }

    /*
     * Send given string to database
     * @return ResultSet
     */
    public ResultSet toResultSet() {
        Statement stmt = null;
        ResultSet rs = null;
        // Preform SQL Query
        try {
            stmt = connection.createStatement();
            rs = stmt.executeQuery(this.query);
        } catch (SQLException e) {
            debug(e.getMessage());
        }
        return rs;
    }

    /*
     * Close connection
     * Overrides close()
     * @return 
     */
    public void close() {
        // Close connection (We don't need to keep connection, really)
        if (connection != null) {
            try {
                connection.close();
                debug("Connection closed.");
            } catch (Exception e) {
                debug(e.getMessage());
            }
        }

    }
}
